﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CommonLibraries.DeviceLibrary;
using CommonLibraries.DeviceLibrary.Helpers;

namespace demo
{
    public partial class HomeForm : BaseForm
    {
        public Int32 m_PositionInserted = 0;
        protected Int32 m_PositionSelected = 0;
        protected ViewPhotosForm m_ViewPhotosForm;
        protected PhotoForm m_PhotoForm;
        protected ViewDetailsForm m_ViewDetailsForm = null;

        public HomeForm()
        {
            InitializeComponent();
            this.buttonFocus.Focus();
        }

        public void SavePosition()
        {
            try
            {
                string stemp = "";
                // fetch values
                double _Longitude;
                _Longitude = ConvertLongitudeToDecimal(m_GPS.NmeaGGA.Longitude, m_GPS.NmeaGGA.LongitudeHemisphere, ref stemp);

                double _Latitude;
                _Latitude = ConvertLatitudeToDecimal(m_GPS.NmeaGGA.Latitude, m_GPS.NmeaGGA.LatitudeHemisphere, ref stemp);

                double _Altitude;
                _Altitude = double.Parse(m_GPS.NmeaGGA.Altitude.ToString());

                DateTime _Time = System.DateTime.Now;
                if(m_GPS.HasSolution)
                    _Time = m_GPS.NmeaGGA.SateliteTime;

                double _Angle;
                _Angle = GetCompassAngle();
                // insert new record

                using (demo.demoDataSetTableAdapters.tb_PositionsTableAdapter _tb_PositionTableAdapter = new demo.demoDataSetTableAdapters.tb_PositionsTableAdapter())
                {
                    demoDataSet.tb_PositionsDataTable _Table;
                    _Table = new demoDataSet.tb_PositionsDataTable();

                    demoDataSet.tb_PositionsRow _Row;
                    _Row = _Table.Addtb_PositionsRow(_Longitude, _Latitude, _Altitude, "", _Angle, m_GPS.NmeaGGA.SateliteCount, _Time, 0);

                    _tb_PositionTableAdapter.Update(_Row);

                    m_PositionInserted = (int)_tb_PositionTableAdapter.GetLastId();
                }
            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("SavePosition->" + ex.InnerException + "\n"+ex.StackTrace);
            }
            
        }
        private float GetCompassAngle()
        {
            try
            {
                if (m_Compass.PowerState == PowerStates.Off)
                    m_Compass.PowerState = PowerStates.On;
                m_Compass.TestCalibration();
                return m_Compass.Angle;

            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("GetCompassAngle->" + ex.InnerException + "\n" + ex.StackTrace);
                return 0;
            }

        }

        public double ConvertLongitudeToDecimal(string Position, string CoordinatedLetter, ref string FormatedView)
        {

            try
            {
                double SingleValue = 1;
                switch (CoordinatedLetter)
                {
                    case "E":
                        SingleValue = 1;
                        break;
                    case "W":
                        SingleValue = -1;
                        break;
                }
                double NewPosition = 0;
                FormatedView = "0";
                if (Position != "0")
                {
                    string[] arrPosition = Position.Split('.');
                    double previewMinutes = double.Parse(arrPosition[0].Substring(3, 2));
                    double previewDegree = double.Parse(arrPosition[0].Substring(0, 3));

                    double previewSeconds = (double.Parse(arrPosition[1]) / 10000000) * 60;
                    FormatedView = previewDegree.ToString() + " ° " + previewMinutes.ToString() + " ' " + previewSeconds.ToString() + " \" ";
                    // 34º 36' 34.79'' = 34 + ( 36 / 60 ) + ( 34,79 / 3600 ) =  (expresado en decimal)
                    NewPosition = (previewDegree + (previewMinutes / 60) + (previewSeconds / 3600)) * SingleValue;
                }
                return NewPosition;
            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("ConvertLongitudeToDecimal->" + ex.InnerException + "\n" + ex.StackTrace);
                return 0;
            }


        }
        public double ConvertLatitudeToDecimal(string Position, string CoordinatedLetter, ref string DegreeFormated)
        {
            try
            {
                double SingleValue = 1;
                switch (CoordinatedLetter)
                {
                    case "N":
                        SingleValue = 1;
                        break;
                    case "S":
                        SingleValue = -1;
                        break;
                }
                double NewPosition = 0;
                DegreeFormated = "0";
                if (Position != "0")
                {
                    string[] arrPosition = Position.Split('.');
                    double previewMinutes = double.Parse(arrPosition[0].Substring(2, 2));
                    double previewDegree = double.Parse(arrPosition[0].Substring(0, 2));
                    double previewSeconds = (double.Parse(arrPosition[1]) / 10000000) * 60;
                    DegreeFormated = previewDegree.ToString() + " ° " + previewMinutes.ToString() + " ' " + previewSeconds.ToString() + " \" ";
                    // 34º 36' 34.79'' = 34 + ( 36 / 60 ) + ( 34,79 / 3600 ) =  (expresado en decimal)
                    NewPosition = (previewDegree + (previewMinutes / 60) + (previewSeconds / 3600)) * SingleValue;
                }
                return NewPosition;
            }
            catch (Exception ex )
            {
                ErrorManager.CreateDebug("ConvertLongitudeToDecimal->" + ex.InnerException + "\n" + ex.StackTrace);
                return 0;
            }


        }


        private void transparentLabelRecord_Click(object sender, EventArgs e)
        {
            record();
        }

        private void record()
        {
            try
            {
                this.transparentLabelRecord.Enabled = false;
                SavePosition();
                OpenPhotoForm();
                this.transparentLabelRecord.Enabled = true;

            }
            catch (Exception ex)
            {
                ErrorManager.CreateDebug("ConvertLongitudeToDecimal->" + ex.InnerException + "\n" + ex.StackTrace);
            }
        }

        private void OpenPhotoForm()
        {
            Cursor.Current = Cursors.WaitCursor;
            m_PhotoForm = new PhotoForm();
            m_PhotoForm.SetPositionId = m_PositionInserted;
            Cursor.Current = Cursors.Default;
            m_PhotoForm.ShowDialog();
            m_PhotoForm.Dispose();
            this.buttonFocus.Focus();
            this.UpdateData();
            
        }

        private void transparentLabelExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void HomeForm_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'demoDataSet.tb_Positions' table. You can move, or remove it, as needed.
            this.tb_PositionsGridTableAdapter.Fill(this.demoDataSet.tb_PositionsGrid);

        }

        public void UpdateData()
        {
            tb_PositionsGridTableAdapter.Fill(demoDataSet.tb_PositionsGrid);
            //tb_PositionsGridTableAdapter.Update(demoDataSet);

        }

        private void menuItemDeleteRecord_Click(object sender, EventArgs e)
        {
            // get current row

            Int32 _RowIndex;
            _RowIndex = this.gridHistory.CurrentRowIndex;
            demoDataSet.tb_PositionsGrid.Rows[_RowIndex].Delete();
            demoDataSetTableAdapters.tb_PositionsTableAdapter tb_PositionsTableAdapter = new demo.demoDataSetTableAdapters.tb_PositionsTableAdapter();
            tb_PositionsTableAdapter.DeletePosition(m_PositionSelected);
            tb_PositionsTableAdapter.Dispose();
            ImageHelper.DeleteImagesByPosition(m_PositionSelected.ToString(), Constants.K_ImagesFolder);
            UpdateData();
        }
        /// <summary>SHOWS CONTEXT MENU ON THE SELECTED POSITION OF THE DATA GRID</summary>
        void gridHistory_DoubleClick(object sender, System.EventArgs e)
        {
            try
            {
                if (this.gridHistory.CurrentRowIndex < 0)
                    return;
                /*Datagrid
                    0: Id
                    1: Time
                    2: Number of satellites
                    3: Total Images

                */
                m_PositionSelected = Int32.Parse(this.gridHistory[this.gridHistory.CurrentRowIndex, 0].ToString());
                int x = Control.MousePosition.X - 100;
                int y = Control.MousePosition.Y - 100;
                Point _Position = new Point(x, y);

                DataGridCell _DataGridCell;
                _DataGridCell = new DataGridCell(this.gridHistory.CurrentRowIndex, 0);
                this.gridHistory.CurrentCell = _DataGridCell;
                this.gridHistory.Select(this.gridHistory.CurrentRowIndex);


                this.GridContextMenu.Show(this.gridHistory, _Position);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void menuItemViewPhotos_Click(object sender, System.EventArgs e)
        {
            m_ViewPhotosForm = new ViewPhotosForm();
            m_ViewPhotosForm.IdPosition = m_PositionSelected;
            m_ViewPhotosForm.ShowDialog();
            m_ViewPhotosForm.Dispose();
            this.buttonFocus.Focus();
        }

        void menuItemViewPosition_Click(object sender, System.EventArgs e)
        {
            m_ViewDetailsForm = new ViewDetailsForm();
            m_ViewDetailsForm.IdPosition = m_PositionSelected;
            m_ViewDetailsForm.ShowDialog();
            m_ViewDetailsForm.Dispose();
            this.buttonFocus.Focus();
        }

        public override void buttonFocus_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            switch (e.KeyValue)
            {
                case 13:
                    record();
                    break;
                case 27:
                    this.Close();
                    break;
            }
        }

        

    }
}